package com.rosh.rpc.client.discovery.zk;

import com.rosh.rpc.client.cache.ServiceProviderCache;
import com.rosh.rpc.client.discovery.RpcServiceDiscovery;
import com.rosh.rpc.client.utils.ZkClientUtils;
import com.rosh.rpc.core.provider.ServiceProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description:
 * @Author: rosh
 * @Date: 2022/6/14 00:36
 */
@Slf4j
@Component
public class ZkServiceDiscovery implements RpcServiceDiscovery {

    @Autowired
    private ZkClientUtils zkClientUtils;

    @Autowired
    private ServiceProviderCache serviceProviderCache;


    /**
     * 完成服务发现
     */
    @Override
    public void serviceDiscovery() {

        //拉取所有服务列表
        List<String> serviceList = zkClientUtils.getServiceList();
        if (CollectionUtils.isNotEmpty(serviceList)) {
            //遍历所有接口
            for (String serviceName : serviceList) {
                //获取接口下provider 信息
                List<ServiceProvider> providers = zkClientUtils.getServiceInfos(serviceName);
                //将接口存入缓存
                log.info("接口名称为:{},服务提供者为:{}", serviceName, providers);
                serviceProviderCache.put(serviceName, providers);
                //订阅变更事件
                zkClientUtils.subscribeZKEvent(serviceName);
            }
        }

    }
}
